package com.dongdongshop.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdongshop.constant.AliyunConstant;
import com.dongdongshop.util.Result;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import wiremock.net.minidev.json.JSONObject;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("message")
public class MessageController {

    @Autowired
    private StaticCredentialProvider provider;

    @RequestMapping("sendPhone")
    @ResponseBody
    public Result sendPhone(String phone){
        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou") // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        // Parameter settings for API request
        JSONObject json = new JSONObject();
        String number = RandomUtil.randomNumbers(4);
        json.put(AliyunConstant.SMS_CODE,number);
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName(AliyunConstant.SIGN)
                .templateCode(AliyunConstant.TEMPLATECODE)
                .templateParam(json.toJSONString())
                .build();
        // Asynchronously get the return value of the API request
        try {
            CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
            // Synchronously get the return value of the API request
            SendSmsResponse resp = response.get();
            System.out.println(new Gson().toJson(resp));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }finally {
            client.close();
        }
        return Result.OK();
    }
}
